package com.sc.sc250601.cook.service.impl;

import com.sc.sc250601.cook.mapper.CommentMapper;
import com.sc.sc250601.cook.pojo.Comment;
import com.sc.sc250601.cook.pojo.CommentDTO;
import com.sc.sc250601.cook.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.soap.Text;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    CommentMapper commentMapper;

    public List<Comment> selectAllByTidAndType(Long tid, Integer type) {
        return null;
    }

    @Override
    public List<CommentDTO> getComments(Integer targetType, Long targetId) {
        // 获取指定类型帖子的所有评论，带用户信息
        List<CommentDTO> all = commentMapper.selectCommentsWithUser(targetType, targetId);
        // 处理父子评论
        HashMap<Long, CommentDTO> map = new HashMap<>();
        for (CommentDTO dto : all) {
            map.put(dto.getId(), dto);
        }
        List<CommentDTO> roots = new ArrayList<>();
        for(CommentDTO dto : all){
            if (dto.getParentId() == null) {
                // 顶级评论
                roots.add(dto);
            } else {
                // 子评论
                CommentDTO parent = map.get(dto.getParentId());
                if (parent != null) {
                    parent.getChildren().add(dto);
                }
            }
        }
        return roots;
    }

    public int addComment( Comment comment) {
        return  commentMapper.insert(comment);

    }
}
